package cn.aws360.boot.auth.api.helper;

import cn.aws360.boot.auth.api.constant.AuthConstant;
import cn.aws360.boot.auth.api.pojo.response.LoginUserModel;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author junnan
 */
@Slf4j
public class LoginHelper {

    public static String login(LoginUserModel loginUserModel) {
        Integer userId = loginUserModel.getId();
        SaHolder.getStorage().set(AuthConstant.CACHE_LOGIN_USER, loginUserModel);
        StpUtil.login(userId);
        StpUtil.getTokenSession().set(AuthConstant.CACHE_LOGIN_USER, loginUserModel);
        String token = StpUtil.getTokenValue();
        log.info("【登录成功】userId: {}, token: {}", userId, token);
        return token;
    }

    public static void logout() {
        Integer userId = getUserId();
        StpUtil.logout();
        log.info("【退出成功】userId: {}", userId);
    }

    public static LoginUserModel getLoginUser() {
        try {
            LoginUserModel loginUserModel = (LoginUserModel) SaHolder.getStorage().get(AuthConstant.CACHE_LOGIN_USER);
            if (ObjectUtil.isNotNull(loginUserModel)) {
                return loginUserModel;
            }

            loginUserModel = (LoginUserModel) StpUtil.getTokenSession().get(AuthConstant.CACHE_LOGIN_USER);
            SaHolder.getStorage().set(AuthConstant.CACHE_LOGIN_USER, loginUserModel);
            return loginUserModel;
        } catch (Exception e) {
            return null;
        }
    }

    public static Integer getUserId() {
        LoginUserModel loginUserModel = getLoginUser();
        if (ObjectUtil.isNull(loginUserModel)) {
            return 0;
        }
        return loginUserModel.getId();
    }

    public static String getUsername() {
        LoginUserModel loginUserModel = getLoginUser();
        if (ObjectUtil.isNull(loginUserModel)) {
            return null;
        }
        return loginUserModel.getUsername();
    }

    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        return BCrypt.checkpw(rawPassword, encodedPassword);
    }

    public static String encryptPassword(String password) {
        return BCrypt.hashpw(password);
    }

}
